<?php
namespace Demo\App\Task;

use Demo\App\Model\TestModel;
use PhpAmqpLib\Connection\AMQPStreamConnection;
use PhpAmqpLib\Message\AMQPMessage;
use Swork\Bean\Annotation\Inject;
use Swork\Bean\Annotation\Timeout;
use Swork\Bean\Annotation\TimerTask;
use Swork\Bean\Annotation\Reference;
use Swork\Bean\BeanCollector;
use Swork\Service;

class TestTask extends BeanCollector
{
    /**
     * @Inject()
     * @var TestModel
     */
    private $testModel;

    /**
     * @Reference("user")
     * @var \Demo\App\Service\TestInterface
     */
    private $testInterface;

    /**
     * 每1秒
     * @TimerTask(1000)
     */
    function test01()
    {
        Service::$logger->info('TimerTask-1 >>> ' . time());

        //Tasker::deliver(self::class, 'test04');
    }

    /**
     * 每1秒
     * @TimerTask(0)
     * @throws
     */
    function wsTask()
    {
        var_dump('wsTask >>> ' . microtime(true));
        $connection = new AMQPStreamConnection('localhost', 5672, 'guest', 'guest');
        $channel = $connection->channel();

        //队列声明
        $queue_name = 'task_queue1';
        $channel->queue_declare($queue_name, false, true, false, false);

        //发送消息到rabbitmq
        $msg = new AMQPMessage('time >>> ' . microtime(true));
        $channel->basic_publish($msg, '', $queue_name);

        $channel->close();
        $connection->close();
    }

    /**
     * 每1秒
     * @TimerTask(500)
     */
    function test02()
    {
        Service::$logger->info('TimerTask-2 >>> ' . time());

        //Tasker::deliver(self::class, 'test04');
    }

    /**
     * 任务3
     * @TimerTask(3000)
     * @Timeout(1)
     */
    function test03()
    {
        Service::$logger->info('TimerTask-3 >>> ' . time());
//        return [1, 3, 4, 5];
    }

    /**
     * 分布式裂变式的任务，在执行完后，会生产多个子任务（每2秒执行一次）
     * @TimerTask("group1", 2000)
     * @Timeout(2)
     */
    function test04()
    {
        echo 'TimerTask-4 >>> ' . time() . PHP_EOL;
        $result = $this->testInterface->info(1, 2);
        var_dump('test4 rpc >>> ' . json_encode($result));
        return [1, 3, 4, 5, 6, 8, 9];
    }

    /**
     * 分布式子任务（与裂变式的任务配合）
     * @TimerTask("group1")
     * @param $arg
     */
    function test05($arg)
    {
        $result2 = $this->testModel->getCount();
        $result = $this->testInterface->mysql();
        var_dump('test5 rpc >>> ' . json_encode($result));
        echo 'TimerTask-5 -['. $arg .'] >>> ' . time() .' - '. $result2 . PHP_EOL;
    }
}
